package com.multi.source.service.impl;

import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.multi.source.domain.BkDataSourceInfo;
import com.multi.source.mapper.SystemDbMapper;
import com.multi.source.service.SystemDbService;
import com.multi.source.util.DataBaseUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * @Description 底层通用数据库接口实现
 * @ClassName SystemDbServiceImpl
 * @Author pzj
 * @Data 2024/11/22 14:27
 */
@Slf4j
@Service
public class SystemDbServiceImpl implements SystemDbService {

    @Autowired
    private DataBaseUtils dataBaseUtils;

    @Autowired
    private SystemDbMapper systemDbMapper;

    /**
     * 创建租户关联数据库
     *
     * @param bkDataSourceInfo
     * @return
     */
    @Override
    @DSTransactional
    public Boolean createDataSource(BkDataSourceInfo bkDataSourceInfo) {
        //临时创建数据库连接
        dataBaseUtils.createConnect(bkDataSourceInfo,"mysql");
        //创建数据库
        systemDbMapper.createDataSource(bkDataSourceInfo.getDbIp(),bkDataSourceInfo.getDbName());
        //删除临时创建的数据库连接
        dataBaseUtils.deleteConnect(bkDataSourceInfo.getDbIp());
        //创建新的稳定连接
        dataBaseUtils.createConnect(bkDataSourceInfo);
        //读取sql文件创建租户数据库
        dataBaseUtils.createDataTable(bkDataSourceInfo);
        return Boolean.TRUE;
    }
}
